package com.mjk.manager.monitor.work;

import cn.hutool.core.exceptions.ExceptionUtil;
import com.mjk.common.base.error.BeeError;
import com.mjk.common.base.response.BeeResponse;
import com.mjk.common.base.work.BaseWork;
import com.mjk.common.base.work.annotation.BeeWork;
import com.mjk.common.core.redis.datatype.RedisHashUtils;
import com.mjk.common.tools.monitor.IMonitor;
import com.mjk.common.util.FileUtils;
import com.mjk.common.web.getway.restful.prototal.websocket.impl.WebSocketServer;
import com.mjk.manager.monitor.dto.MonitorDto;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@SuppressWarnings("SpringJavaInjectionPointsAutowiringInspection")
@BeeWork(work = "monitor")
public class MonitorWork  extends BaseWork {
	@Autowired
	private IMonitor monitor;
	@Value(value = "${server.port:8080}")
	private int nodePort;
	@Autowired
	private RedisTemplate redisTemplate;
	@Autowired
	private WebSocketServer webSocketServer;

	/**
	 * 获取服务器信息
	 *
	 * @param dto
	 * @return
	 */
	public BeeResponse getServiceList(MonitorDto dto) {
		return BeeError.BEE_SUC.tranceError(monitor.getServices(dto.getServiceName()));
	}

	/**
	 * 获取单节点下 所存在的服务版本
	 *
	 * @param dto 打包服务的目录结构为
	 *            bin  批处理命令
	 *            conf 配置文件
	 *            lib  jar包路径
	 *            ***.jar  启动包路径
	 *            update  更新目录
	 *            backup  备份目录
	 * @return backup目录下面的目录列表
	 */
	public BeeResponse getNodeServiceVersion(MonitorDto dto) {
		needParams(dto, MonitorDto::getServicePath);
		File file = new File(dto.getServicePath() + "/backup/");
		//备份文件只保留3个版本
		FileUtils.deleteOldFile(dto.getServicePath() + "/backup/", 3);
		File[] files = file.listFiles();
		List<Map<String, String>> versions = new ArrayList<>();
		if (null != files && files.length > 0) {
			for (File tmp : files) {
				if (tmp.isDirectory()) {
					Map<String, String> map = new HashMap<>();
					map.put("version", tmp.getName());
					versions.add(map);
				}
			}
		}
		return BeeError.BEE_SUC.tranceError(versions);
	}


	/**
	 * 执行服务
	 * 1启动
	 * 2回滚 需要指定回滚版本
	 *
	 * @param dto
	 * @return
	 */
	public BeeResponse doExec(MonitorDto dto) {
		needParams(dto, MonitorDto::getServicePath, MonitorDto::getServiceIp);
		String commndPath = dto.getServicePath() + "/bin/";
		String commndStart = "cmd /c  ";
		Process process;
		try {
			switch (dto.getExecType()) {
				case "1":
					//当前服务版本更新的次数
					int nowNum = RedisHashUtils.incr(redisTemplate, dto.getServiceIp() + dto.getServiceName(), dto.getVersionNum());
					needParams(dto, MonitorDto::getVersionNum, MonitorDto::getPort);
					String cmd = commndStart + commndPath.replace(" ", "\" \"") +
							"restart.bat " + dto.getVersionNum() + " " + dto.getPort() + " " + nowNum;
					process = Runtime.getRuntime().exec(cmd);
					break;
				case "2":
					needParams(dto, MonitorDto::getVersionNum);
					process = Runtime.getRuntime().exec(commndStart + "\"" + commndPath + "\"" + "rollback.bat \"" + commndPath + "\" " + dto.getVersionNum() + " " + dto.getPort());
					break;
				default:
					return BeeError.BEE_ERROR_FOR_ADMIN.tranceError();
			}
			if (process.waitFor() == 0) {
				return BeeError.BEE_SUC.tranceError();
			} else {
				return BeeError.BEE_ERROR_FOR_ADMIN.tranceError();
			}
		} catch (Exception e) {
			Thread.currentThread().interrupt();
			return BeeError.BEE_ERROR_FOR_ADMIN.tranceError(ExceptionUtil.getMessage(e));
		}
	}
}
